/******************************************************************************************************
Copyright (C) 2013 Mestrelab Research S.L. All rights reserved.

This file is part of the Mnova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals settings, Dir, Dialog, qsTr, FileDialog, print, GroupBox, LineEdit, ToolButton, MessageBox, getMaskFilesAdv, dbOpenDatabase, Resumable, ProgressDialog, serialization, DBPlugin, Application, dbMakeDBItems, MnUi*/
/*jslint plusplus: true, indent: 4*/

function dbImportFilesPairwise() {
	"use strict";
	var mainDir, optDir, mainFiles, optFiles, dbname, resumable, progress, startTime, oldFileHistory,
		mainFileCount, optFileCount, dbDef, f, files, dw, startTimeDoc, dbItems, cid,
	// Choose files
		settingsKey = "Database/Import Files Pairwise",
		mainDirSettingsKey = settingsKey + "/Last Directory/Main",
		mainFileMaskKey = settingsKey + "/File Mask/Main",
		optFilesKey = settingsKey + "/Optional Files",
		optDirSettingsKey = settingsKey + "/Last Directory/Opt",
		optFileMaskKey = settingsKey + "/File Mask/Opt",
		resumeSettingsKey = settingsKey + "/Resume",

		mainDirName = settings.value(mainDirSettingsKey, Dir.home()),
		optDirName = settings.value(optDirSettingsKey, Dir.home()),
		msgDirNotExists = qsTr("Directory '{0}' does not exist."),

		dialog = new Dialog(),
		gbMain = new GroupBox(),
		leMainDirectory = new LineEdit(),
		tbOpenMainDir = new ToolButton(),
		leMainFileMask = new LineEdit(),
		gbOpt = new GroupBox(),
		leOptDirectory = new LineEdit(),
		tbOpenOptDir = new ToolButton(),
		leOptFileMask = new LineEdit();

	dialog.title = qsTr("Import Files");
	dialog.onOpenDir = function () {
		var dirName = this.text;
		dirName = FileDialog.getExistingDirectory(dirName);
		print("Directory: " + dirName);
		if (dirName) {
			this.text = dirName;
		}
	};

	gbMain.title = qsTr("Main Files");
	dialog.add(gbMain);

	leMainDirectory.label = qsTr("Base Directory:");
	leMainDirectory.text = mainDirName;

	tbOpenMainDir.text = "...";
	tbOpenMainDir.clicked.connect(leMainDirectory, dialog.onOpenDir);
	gbMain.add(leMainDirectory, tbOpenMainDir);

	leMainFileMask.label = qsTr("Path Mask:");
	leMainFileMask.text = settings.value(mainFileMaskKey, "");
	leMainFileMask.toolTip = qsTr("Examples:\nPRJ ??????/*.fid/*.mol\nSMPL-*/10/pdata/1r");
	gbMain.add(leMainFileMask);

	gbOpt.title = qsTr("Optional Files");
	gbOpt.checkable = true;
	gbOpt.checked = settings.value(optFilesKey, false);
	dialog.add(gbOpt);

	leOptDirectory.label = qsTr("Base Directory:");
	leOptDirectory.text = optDirName;

	tbOpenOptDir.text = "...";
	tbOpenOptDir.clicked.connect(leOptDirectory, dialog.onOpenDir);
	gbOpt.add(leOptDirectory, tbOpenOptDir);

	leOptFileMask.label = qsTr("Path Mask:");
	leOptFileMask.text = settings.value(optFileMaskKey, "");
	leOptFileMask.toolTip = qsTr("Examples:\nPRJ ??????/*.mol/fid\nSMPL-*/10/pdata/*.mol");
	gbOpt.add(leOptFileMask);

	if (!dialog.exec()) {
		return;
	}

	print("Directory: " + leMainDirectory.text);
	print("File Mask: " + leMainFileMask.text);

	mainDirName = leMainDirectory.text;
	mainDir = new Dir(mainDirName);
	if (!mainDirName || !mainDir.exists) {
		MessageBox.critical(msgDirNotExists.format(mainDirName));
		return;
	}

	optDirName = leOptDirectory.text;
	optDir = new Dir(optDirName);
	if (!optDirName || !optDir.exists) {
		MessageBox.critical(msgDirNotExists.format(optDirName));
		return;
	}

	settings.setValue(mainDirSettingsKey, mainDirName);
	settings.setValue(mainFileMaskKey, leMainFileMask.text);
	settings.setValue(optFilesKey, gbOpt.checked);
	settings.setValue(optDirSettingsKey, optDirName);
	settings.setValue(optFileMaskKey, leOptFileMask.text);

	mainFiles = getMaskFilesAdv(mainDir, leMainFileMask.text, mainDir.Name, mainDir.Name);
	mainFiles.sort(Dir.numericPathsCompare);
	print("Main Files Found: " + mainFiles);
	//MessageBox.information("Main Files Found: " + mainFiles);

	if (!mainFiles.length) {
		MessageBox.warning(qsTr("No files matching to the specified main path mask found."));
		return;
	}

	optFiles = [];
	if (gbOpt.checked) {
		optFiles = getMaskFilesAdv(optDir, leOptFileMask.text, optDir.Name, optDir.Name);
		optFiles.sort(Dir.numericPathsCompare);
		print("Optional Files Found: " + optFiles);
	}
	print("Optional Files Found: " + optFiles);

	// Choose database
	dbname = dbOpenDatabase();
	if (!dbname) {
		return;
	}

	// Show resume dialog
	resumable = new Resumable(resumeSettingsKey, 1, Math.max(mainFiles.length, optFiles.length), "Import Files");
	resumable.dialogMessage = qsTr("Found <b>{0}</b> main files ").format(mainFiles.length);
	if (optFiles.length > 0) {
		resumable.dialogMessage += qsTr(" and <b>{0}</b> optional files ").format(optFiles.length);
	}
	resumable.dialogMessage += qsTr("for import into database <b>{0}</b>.").format(dbname);
	if (!resumable.init()) {
		return;
	}

	// Show progress dialog 
	progress = new ProgressDialog();
	progress.labelText = qsTr("Importing...");
	progress.setRange(0, Math.max(mainFiles.length, optFiles.length));
	progress.show();

	// Import files
	startTime = new Date();
	print("It is now " + startTime.toString());
	oldFileHistory = serialization.fileHistory;
	serialization.fileHistory = false;
	mainFileCount = 0;
	optFileCount = 0;

	dbDef = DBPlugin.client.definition(DBPlugin.client.database);

	for (f = resumable.minValue - 1; f < resumable.maxValue && !progress.wasCanceled; ++f) {
		// Update progress dialog
		progress.value = f;
		Application.mainWindow.processEvents();

		// Update resumable
        resumable.setValue(f + 1);

		files = [];
		if (f < mainFiles.length) {
			files.push(mainFiles[f]);
		}
		if (f < optFiles.length) {
			files.push(optFiles[f]);
		}
		dw = Application.mainWindow.newDocument();
		serialization.open(files);
		print(" Opened ok: " + dw.itemCount() + " items.");
		startTimeDoc = new Date();
        dbItems = dbMakeDBItems(DBPlugin.client, dbDef, true, false);
		cid = DBPlugin.addRecord(DBPlugin.client, dbItems);
		if (cid > 0) {
			print("Saved " +  dbItems.length + " items to record " + cid + " in " + ((new Date() - startTimeDoc) / 1000) + " seconds.");
			mainFileCount++;
			optFileCount = optFileCount + files.length - 1;
		} else {
			MessageBox.critical(qsTr("Error while saving."));
		}
		dw.close();
	}
	if (!progress.wasCanceled) {
		resumable.setValue(0);
	}
	progress.close();
	serialization.fileHistory = oldFileHistory;
    MessageBox.information(qsTr("Imported <b>{0}</b> main files and <b>{1}</b> optional files into database <b>{2}</b>.").format(mainFileCount, optFileCount, dbname));
	print("All done in " + ((new Date() - startTime) / 1000) + " seconds.");
}

if (this.MnUi && MnUi.scripts_db) {
	MnUi.scripts_db.scripts_db_ImportFilesPairwise = dbImportFilesPairwise;
}
